package org.example;


import com.alibaba.fastjson2.JSON;

import static com.alibaba.fastjson2.JSONWriter.Feature.LargeObject;

public class Main {

    static final String userNamePre = "测试名称 c++/go/cangjie 编程语言 json序列化、反序列化性能大比拼 - ";
    static final float scoreBase = 65.5f;
    static final int ageBase = 18;

    public static void main(String[] args) {
        JSON.config(LargeObject, true); // 使用大对象，否则会报oom

        int num = 1000000; // 初始化100万个对象 1000000
        Stu[] stuSlice = new Stu[num];
        InitStu(num, stuSlice);

        final String jsString = JSON.toJSONString(new Response(200, "成功", stuSlice));
        Response resp = null;
        // ↑↑↑  以上构建json字符串的过程我们跳过计时，因为json序列化已经在前一个场景测试结束了 ↑↑↑

        final long startTime = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            resp = JSON.parseObject(jsString, Response.class);
        }

        System.out.printf("json字符串反序列化后信息——code：%d, msg:%s, listLen: %d\n", resp.code, resp.msg, resp.list.length);
        long cos = (System.currentTimeMillis() - startTime) / 10;
        System.out.println("100万个对象(Stu) json 文本反序列化，单次平均耗时(ms)：" + cos);
    }


    static void InitStu(int num, Stu[] stuSlice) {
        for (int i = 0; i < num; i++) {
            Stu tmpStu = new Stu(userNamePre + i, i % 2, ageBase + i, scoreBase + i);
            stuSlice[i] = tmpStu;
        }
    }
}

class Response {
    public int code;
    public String msg;
    public Stu[] list;

    public Response(int code, String msg, Stu[] list) {
        this.code = code;
        this.msg = msg;
        this.list = list;
    }
}

class Stu {
    public String name;
    public int sex;
    public int age;
    public float score;

    public Stu(String name, int sex, int age, float score) {
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.score = score;
    }
}